<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="https://cdn.staticfile.org/openlayers/4.6.5/ol.css">
    <script src="https://cdn.staticfile.org/openlayers/4.6.5/ol.js"></script>
    <!-- <script src="https://code.jquery.com/jquery-3.5.1.min.js"></script> -->
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

    <style>
        html,body,
        #map{
            height: 100%;
            width: 100%;
        }
    </style>
</head>

<body>
    <div id="top">
        北纬：<input type="text" id="north">
        东经：<input type="text" id="east">
        <button style="background-color: orange;color: white;border: none;" onclick="reset()">重置</button>
        <button style="background-color: orange;color: white;border: none;" onclick="locationPoint()">定位</button>
        <button style="background-color: orange;color: white;border: none;" onclick="save()">保存</button>
        <button style="background-color: orange;color: white;border: none;" onclick="getLocation()">测试获取地点名称</button>
        <div>
            <input type="hidden" id="locationval"/>
        </div>
    </div>

    <!-- 地图的挂载点 -->
    <div id="map">
    </div>

    <div id="bottom">
        开始日期：<input type="date">
        结束日期：<input type="date">
        <button style="background-color: orange;color: white;border: none;">保存</button>
    </div>
    
    <script type="text/javascript">
        // import {captchaApi,loginApi} from "@/api/login";// 按需导入

        var northlocation = '';
        var eastlocation = '';
        var locationname = '';
        
        var map = new ol.Map({
            target:'map',//挂载地图
            // 设置图层
            layers:[
                new ol.layer.Tile({
                    source: new ol.source.XYZ({
                        url:'http://t0.tianditu.gov.cn/vec_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=vec&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=95c9ea352c458a3b5629ab6f9276b740'
                    })
                }),
                new ol.layer.Tile({
                    source: new ol.source.XYZ({
                        url:'http://t0.tianditu.gov.cn/cva_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cva&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=95c9ea352c458a3b5629ab6f9276b740'
                    })
                }),
                new ol.layer.Tile({
                    source: new ol.source.XYZ({
                        url:'http://t0.tianditu.gov.cn/eia_c/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=eia&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=95c9ea352c458a3b5629ab6f9276b740'
                    })
                }),
            ],
            //地图视角
            view:new ol.View({
                zoom:5,//初始层级
                center:[106,27],//初始的视图中心位置
                projection:"EPSG:4326"//设置成84坐标系才能使用经纬度坐标
            })
        })

        //创建geojson数据
        var data = {
            type: "FeatureCollection",
            features: [
                {
                    type: "Feature",
                    geometry: {
                        type: "Point",
                        coordinates: [114.30, 30.50]
                    }
                }
            ]
        }

        //将数据添加到矢量数据源中
        var source = new ol.source.Vector({
            /* 将geojson数据设置给实例数据源 */
            features: new ol.format.GeoJSON().readFeatures(data)
        })
        //设置矢量图层，放置矢量数据源
        var layer = new ol.layer.Vector({
            source
        })
        //设置涂层的样式
        const style = new ol.style.Style({
            image:new ol.style.Circle({
                radius:10,
                fill:new ol.style.Fill({
                    color:"#ff2d51"
                }),
                stroke:new ol.style.Stroke({
                    color:"333"
                })
            })
        })
        layer.setStyle(style)
        //添加矢量图层到地图容器
        map.addLayer(layer);

        //在地图上点击一个数据源，添加一个点要素
        //首先构建矢量数据源和矢量图层
        var source = new ol.source.Vector({});
        var layer = new ol.layer.Vector({
            source
        })
        map.addLayer(layer);

        //给地图绑定一个点击事件
        map.on("click",(evt)=>{
            // console.log(evt)
            var {coordinate} = evt;
            console.log(coordinate);//地图的坐标
            console.log(coordinate[1]);//地图的经度  东经
            console.log(coordinate[0]);//地图的纬度  北纬

            eastlocation = coordinate[0];
            northlocation = coordinate[1];
            //构建要素
            var point = new ol.Feature({
                geometry:new ol.geom.Point(coordinate)
            })
            source.addFeature(point);


            // var locationObj = [northlocation,eastlocation]
            

            //实现飞行视角-漫游
            const view = map.getView();
            view.animate({
                center:coordinate
            })

            document.getElementById("north").value=coordinate[1];
            document.getElementById("east").value=coordinate[0];
        })

        function reset(){
            document.getElementById("north").value="";
            document.getElementById("east").value="";
        }

        function getLocation(){
            //1. 创建XMLHttpRequest
            var xmlhttprequest = new XMLHttpRequest();
            northlocation = document.getElementById("north").value
            eastlocation = document.getElementById("east").value

            // var url = "https://api.tianditu.gov.cn/geocoder?postStr={%22lon%22:%22+\'eastlocation'+%22,%22lat%22:%22+\'northlocation'+%22,%22ver%22:%222.0%22}&type=geocode&tk=95c9ea352c458a3b5629ab6f9276b740";
            // var url = "https://api.tianditu.gov.cn/geocoder?postStr={%22lon%22:%22+\'eastlocation\'+%22,%22lat%22:%22+\'northlocation\'+%22,%22ver%22:%222.0%22}&type=geocode&tk=95c9ea352c458a3b5629ab6f9276b740";
            // var url = "https://api.tianditu.gov.cn/geocoder?postStr={%22lon%22:%22"+eastlocation+"%22,%22lat%22:%22"+northlocation+"%22,%22ver%22:%222.0%22}&type=geocode&tk=95c9ea352c458a3b5629ab6f9276b740";
            // var url = "https://api.tianditu.gov.cn/geocoder?postStr={%22lon%22:%22eastlocation%22,%22lat%22:%22northlocation%22,%22ver%22:%222.0%22}&type=geocode&tk=95c9ea352c458a3b5629ab6f9276b740";
            // var url = "https://api.tianditu.gov.cn/geocoder?postStr={%22lon%22:%22+eastlocation+%22,%22lat%22:%22+northlocation+%22,%22ver%22:%222.0%22}&type=geocode&tk=95c9ea352c458a3b5629ab6f9276b740";
            var url = `https://api.tianditu.gov.cn/geocoder?postStr={"lon":"${eastlocation}","lat":"${northlocation}","ver":"2.0"}&type=geocode&tk=95c9ea352c458a3b5629ab6f9276b740`;

            // return fetch(url)
            //     .then(response => response.json()) // 将响应解析为JSON对象
            //     .then(data => {
            //         // 在这里可以访问和处理获取到的对象
            //         console.log(data);
            //     })
            //     .catch(error => {
            //         // 处理错误
            //         console.error(error);
            //     });

            // 2. 调用open方法设置请求参数
            xmlhttprequest.open("GET",url,true)

            //4. 在send方法前绑定 onreadystatechange 请求，处理请求完成后的操作
            xmlhttprequest.onreadystatechange = function(){
                if(xmlhttprequest.readyState == 4 && xmlhttprequest.status == 200){
                    var jsonObj = JSON.parse(xmlhttprequest.responseText);
                    //把相应的数据进行弹窗显示
                    // console.log(jsonObj);
                    // console.log(jsonObj.result);
                    console.log(jsonObj.result.addressComponent.address);
                    console.log(typeof(jsonObj.result.addressComponent.address))
                    // alert(jsonObj);
                    document.getElementById("locationval").value = jsonObj.result.addressComponent.address;

                    locationname = document.getElementById("locationval").value
                    console.log(locationname);
                }
            }

            //3. 调用send方法发送请求
            xmlhttprequest.send();
        }

        // locationname = document.getElementById("locationval").value
        // console.log(locationname);
        

        function save(){
            //1. 创建XMLHttpRequest
            var xmlhttprequest = new XMLHttpRequest();
            //2. 调用open方法设置请求参数
            xmlhttprequest.open("POST","http://localhost:8888/gpspoint/save",true)
            xmlhttprequest.setRequestHeader("Content-type", "application/json");
            northlocation = document.getElementById("north").value
            eastlocation = document.getElementById("east").value

            locationname = document.getElementById("locationval").value
            console.log(locationname);

            var obj = {
                "id":"",
                // "name":"济南",
                "name":locationname,
                "shape":northlocation+","+eastlocation,
                "time":""
            };

            //3. 调用send方法发送请求
            xmlhttprequest.send(JSON.stringify(obj));

            //4. 在send方法前绑定 onreadystatechange 请求，处理请求完成后的操作
            xmlhttprequest.onreadystatechange = function(){
                if(xmlhttprequest.readyState == 4 && xmlhttprequest.status == 200){
                    var jsonObj = JSON.parse(xmlhttprequest.responseText);
                    //把相应的数据进行弹窗显示
                    console.log(jsonObj);
                    // alert(jsonObj);
                }
            }
            
        }

        function locationPoint(){
            northlocation = document.getElementById("north").value
            eastlocation = document.getElementById("east").value
            
            getDetailLocation(eastlocation,northlocation)

            var locationObj = [eastlocation,northlocation]
            
            //实现飞行视角-漫游
            const view = map.getView();
            view.animate({
                center:locationObj
            })

        }


        //通过经纬度获取详细地址   先经度后纬度
        function getDetailLocation(lnglat_lng, lnglat_lat) {
            var mapKey = "95c9ea352c458a3b5629ab6f9276b740";
            $.ajax({
                url: "https://api.tianditu.gov.cn/geocoder",
                type: 'GET',
                contentType: "application/json;charset=utf-8",
                data: {
                    tk: mapKey,
                    type: "geocode",
                    postStr: "{'lon':" + lnglat_lng + ",'lat':" + lnglat_lat + ",'ver':1}"
                },
                success: (data) => {
                    var addressdata = eval("(" + data + ")");
                    console.log(addressdata);
                    //截取地址信息显示在span上
                    detaillocation = addressdata.result.formatted_address;
                    $("#localInfo").text(detaillocation + "->" + (new Date()).toLocaleDateString());
                    $("#zuobiao").text("坐标->"+lnglat_lng+","+lnglat_lat);
                    console.log(detaillocation);
                    
                    if (addressdata.msg == "ok" && addressdata.status == 0) {
                        //将位置信息设置到标注
                        setMarker(lnglat_lat);
                    } else {
                        //dosomething
                    }
                },
                error: (er, er1, er2) => {
                    alert("获取失败");
                }
            });

        }

        //设置标注
        // function setMarker(e) {
        //     var marker = new T.Marker(e);
        //     map.addOverLay(marker);
        //     var markerInfoWin = new T.InfoWindow("" + detaillocation);
        //     marker.addEventListener("click", function() {
        //         marker.openInfoWindow(markerInfoWin);
        //     });
        // }

        function setMarker(e) {
            var marker = new ol.Marker(e);
            map.addOverLay(marker);
            var markerInfoWin = new ol.InfoWindow("" + detaillocation);
            marker.addEventListener("click", function() {
                marker.openInfoWindow(markerInfoWin);
            });
        }

        // function save(){
            
        // }
    </script>
    
</body>
</html>